package factorytest.iflytek.com.einkiflytekfactorytest.engineerui;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.app.ActivityCompat;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;


/**
 * Created by Administrator on 2017/4/2.
 */
public class TouchDrawActivity extends Activity {

    private boolean mViewItemsCreated = false;


    private static final float DEF_ITEM_VIEW_SIZE = 80.0f;

    private float itemViewSize = DEF_ITEM_VIEW_SIZE;

    private Context mContext;

    private RelativeLayout parentContainer;
    Rect rectTemp = new Rect();

    boolean isETP = false;

    private boolean isPcba;

    private TextView txtInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_touchtest);

        txtInfo = (TextView) findViewById(R.id.txtInfo);

        findViewById(R.id.btnFail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishWithFail();
            }
        });

        parentContainer = (RelativeLayout) findViewById(R.id.touch_draw_root_layout);

        isPcba = getIntent().getBooleanExtra("isPcba", false);

        final float size = getResources().getDimension(R.dimen.touch_draw_item_view_size);
        if (size > 0) {
            itemViewSize = size;
            DebugLog.e("touch draw item size = " + size);

        }

        mContext = this;

    }

    @Override
    protected void onResume() {
        super.onResume();

        isETP = getIntent().getBooleanExtra("etp", false);
        DebugLog.i( "onResume isETP = " + isETP);
        String useTool = getString(R.string.tp_test_use_finger);
        if (isETP) {
            useTool = getString(R.string.tp_test_use_electric_pen);
        }
        String info = getString(R.string.tp_test_info, useTool);
        txtInfo.setText(info);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            createAllViewItems();
        }
    }

    private void createAllViewItems(){

        if( mViewItemsCreated )
            return ;
        mViewItemsCreated = true;
        CreateViewItems(mContext, parentContainer);
    }


    private void CreateViewItems(Context context, RelativeLayout parent) {

        parent.removeAllViews();

        int w = parent.getWidth();
        int h = parent.getHeight();

        if (w == 0 || h == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            Display display = getWindowManager().getDefaultDisplay();

            display.getMetrics(dm);
            w = dm.widthPixels;
            h = dm.heightPixels;
        }

        float viewW = itemViewSize;
        float viewH = itemViewSize;
        int itemViewCountHorizontal = (int) (w / itemViewSize);
        int itemViewCountVertical = (int) (h / itemViewSize);
        float deltaW = 1.0f * w % itemViewSize;
        float deltaH = 1.0f * h % itemViewSize;

        viewW += deltaW / itemViewCountHorizontal;
        viewH += deltaH / itemViewCountVertical;

        int index = 0;

        if (isPcba) {

            for (int i = 0; i < itemViewCountVertical; i++) {

                if (i == (itemViewCountVertical / 2)) {

                    int start = itemViewCountHorizontal / 2 - 3;
                    for (int j = start; j < start + 6; j++) {

                        TouchViewItem v = new TouchViewItem(context,
                                j * viewW, i * viewH,
                                (int)viewW, (int)viewH, index++);
                        parent.addView(v);

                    }
                }
            }

        } else {

            for (int i = 0; i < itemViewCountVertical; i++) {

                if (i == 0 || i == (itemViewCountVertical / 2) || i == (itemViewCountVertical - 1)) {

                    for (int j = 0; j < itemViewCountHorizontal; j++) {

                        TouchViewItem v = new TouchViewItem(context,
                                j * viewW, i * viewH,
                                (int)viewW, (int)viewH, index++);
                        parent.addView(v);

                    }
                } else {

                    for (int j = 0; j < 3; j++) {

                        float x = 0;
                        if (j == 1) {
                            x = (j * (itemViewCountHorizontal / 2)) * viewW;

                        } else if (j == 2) {
                            x = ((itemViewCountHorizontal - 1)) * viewW;
                        }

                        TouchViewItem v = new TouchViewItem(context,
                                x, i * viewH,
                                (int) viewW, (int) viewH, index++);

                        parent.addView(v);
                    }
                }
            }
        }


    }

    private void createBtnToFinish() {
        parentContainer.removeAllViews();

        Button btn = new Button(mContext);
        btn.setBackgroundResource(R.drawable.selector_rect_background);
        btn.setTextColor(Color.BLACK);
        btn.setGravity(Gravity.CENTER);
        btn.setElevation(0.0f);

        btn.setText(R.string.tp_click_to_finish);

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMarginStart(20);
        lp.setMarginEnd(20);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        parentContainer.addView(btn, lp);


        setResult(RESULT_OK);
        ActivityCompat.finishAfterTransition(TouchDrawActivity.this);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                setResult(RESULT_OK);
                ActivityCompat.finishAfterTransition(TouchDrawActivity.this);
            }
        });
    }

    private boolean isAllItemGone = false;
    private void checkTouchView(int x , int y){

        boolean allGone = true;
        int count = parentContainer.getChildCount();
        for (int i = 0; i < count; i ++) {
            View view = parentContainer.getChildAt(i);
            if (view instanceof TouchViewItem) {
                TouchViewItem item = (TouchViewItem) view;
                item.getHitRect(rectTemp);
                if (rectTemp.contains(x, y) && item.getVisibility() != View.GONE) {
                    item.setVisibility(View.GONE);
                }

                if (item.getVisibility() == View.VISIBLE) {
                    allGone = false;
                }
            }
        }

        if (allGone) {
            DebugLog.i("items are all gone");
            isAllItemGone = true;
            finishWithOK();
        }

    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int x,y;
        x = (int) event.getX();
        y = (int) event.getY();

        if( event.getAction() == MotionEvent.ACTION_UP ){
            return super.dispatchTouchEvent(event);
        }
        if (event.getPointerCount() == 1
                && !isAllItemGone
                && event.getToolType(0) == (isETP ? MotionEvent.TOOL_TYPE_STYLUS : MotionEvent.TOOL_TYPE_FINGER)) {

            checkTouchView(x, y);
        }

//        Log.e(TAG, "dispatchTouchEvent x = " + x + ",  y = " + y);
        return super.dispatchTouchEvent(event);
    }

    private void finishWithOK() {
        Toast.makeText(mContext, R.string.test_ok, Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        ActivityCompat.finishAfterTransition(this);
    }

    private void finishWithFail() {
        Toast.makeText(mContext, R.string.test_fail, Toast.LENGTH_SHORT).show();
        setResult(RESULT_CANCELED);
        ActivityCompat.finishAfterTransition(this);
    }

    // Button
    public class TouchViewItem extends AppCompatTextView {
        public int mIndex;

        private void init(int index ){
            mIndex = index;
            this.setText(Integer.toString(index));
//            this.setTextSize((float)20.0);
            this.setTextColor(Color.BLACK);
            this.setGravity(Gravity.CENTER);
            this.setClickable(true);
            this.setBackgroundResource(R.drawable.selector_rect_background);
        }

        public TouchViewItem(Context context,float x, float y, int w , int h , int index ) {
            super(context);
//            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            this.setX(x);
            this.setY(y);
            this.setMinimumHeight(h);
            this.setMinimumWidth(w);
            init(index);
        }


        @Override
        public boolean performClick() {
            return super.performClick();
        }
    }


}
